package com.battery.system.service.battery.impl;

import com.battery.common.core.domain.Ztree;
import com.battery.common.core.domain.entity.SysDictData;
import com.battery.common.core.text.Convert;
import com.battery.common.enums.AccountTypeEnum;
import com.battery.common.enums.YesOrNoEnum;
import com.battery.common.json.JSONObject;
import com.battery.common.utils.DateUtils;
import com.battery.system.domain.*;
import com.battery.system.domain.BO.PartnerBO;
import com.battery.system.domain.VO.*;
import com.battery.system.mapper.*;
import com.battery.system.service.ISysConfigService;
import com.battery.system.service.battery.IPartnerService;
import com.battery.system.service.impl.BaseServiceImpl;
import com.battery.system.service.impl.SysConfigServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 合作商Service业务层处理
 *
 * @author battery
 * @date 2021-01-21
 */
@Service
public class PartnerServiceImpl extends BaseServiceImpl<Partner> implements IPartnerService {

    @Autowired
    private PartnerMapper partnerMapper;


    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private ProxyUserMapper proxyUserMapper;


    @Autowired
    private ISysConfigService sysConfigService;


    @Autowired
    private PartnerInstallMapper partnerInstallMapper;

    @Autowired
    private AppUserMapper appUserMapper;


    @Autowired
    private MerchantInstallMapper merchantInstallMapper;


    @Autowired
    private ISysConfigService configService;


    @Autowired
    private Sid sid;

    /**
     * 查询合作商
     *
     * @param id 合作商ID
     * @return 合作商
     */
    @Override
    public Partner selectPartnerById(String id) {
        return partnerMapper.selectPartnerById(id);
    }

    /**
     * 查询合作商列表
     *
     * @param partner 合作商
     * @return 合作商
     */
    @Override
    public List<Partner> selectPartnerList(Partner partner) {
        return partnerMapper.selectPartnerList(partner);
    }

    /**
     * 新增合作商
     *
     * @param partner 合作商
     * @return 结果
     */
    @Override
    public int insertPartner(Partner partner) {
        return partnerMapper.insertPartner(partner);
    }

    /**
     * 修改合作商
     *
     * @param partner 合作商
     * @return 结果
     */
    @Override
    public int updatePartner(Partner partner) {
        partner.setUpdateTime(DateUtils.getNowDate());
        return partnerMapper.updatePartner(partner);
    }

    /**
     * 删除合作商对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deletePartnerByIds(String ids) {
        return partnerMapper.deletePartnerByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除合作商信息
     *
     * @param id 合作商ID
     * @return 结果
     */
    @Override
    public int deletePartnerById(String id) {
        return partnerMapper.deletePartnerById(id);
    }


    @Override
    public List<PartnerVO> selectPartnerVOList(PartnerBO partnerBO) {
        return partnerMapper.selectPartnerVOList(partnerBO);
    }

    /**
     * 添加顶级合作商
     *
     * @param partner
     * @return
     */
    @Transactional
    @Override
    public int addTopLevelPartner(Partner partner) {

        Example example = new Example(Project.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDelete", YesOrNoEnum.NO.getCode());
        Project project = projectMapper.selectOneByExample(example);

        String partnerId = sid.nextShort(); // 合作商ID
        // 添加合作商
        Date date = DateUtils.getNowDate();
        partner.setId(partnerId);
        partner.setSigningTime(date);
        partner.setParentId(null);
        partner.setProjectId(project.getId());
        partner.setShareRatio(new BigDecimal(100).subtract(partner.getProjectShareRatio()));
        partnerMapper.insertPartner(partner);

        // 新增顶级合作商设置表
        String txBrokerage = sysConfigService.selectConfigByKey("sys.system.txBrokerage"); // 默然提现手续费
        String txMinPermit = sysConfigService.selectConfigByKey("sys.system.txMinPermit"); // 提现允许最小金额
        PartnerInstall install = new PartnerInstall();
        install.setPartnerId(partnerId);
        install.setTxBrokerage(new BigDecimal(txBrokerage));
        install.setTxMinPermit(new BigDecimal(txMinPermit));
        partnerInstallMapper.insertPartnerInstall(install);

        // 新增合作商主账号
        ProxyUser proxyUser = new ProxyUser();
        proxyUser.setId(sid.nextShort());// 账号ID
        proxyUser.setPhone(partner.getPhone());
        proxyUser.setTrueName(partner.getFullName());
        proxyUser.setAccountType(AccountTypeEnum.PARTNER.getCode());
        proxyUser.setAccountId(partnerId);
        proxyUser.setCreateTime(DateUtils.getNowDate());

        return proxyUserMapper.insertProxyUser(proxyUser);
    }

    /**
     * 更新顶级合作商
     *
     * @param partner
     * @return
     */
    @Transactional
    @Override
    public int updateTopLevelPartner(Partner partner) {

        Date date = DateUtils.getNowDate();

        Partner partnerBefore = partnerMapper.selectByPrimaryKey(partner.getId());
        // 查询原先账号
        Example example = new Example(ProxyUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("phone", partnerBefore.getPhone());
        criteria.andEqualTo("isDeleted", YesOrNoEnum.NO.getCode());
        criteria.andEqualTo("isStaff", YesOrNoEnum.NO.getCode());
        criteria.andEqualTo("isBan", YesOrNoEnum.NO.getCode());
        criteria.andEqualTo("accountType", AccountTypeEnum.PARTNER.getCode());
        criteria.andEqualTo("accountId", partner.getId());
        ProxyUser proxyUser = proxyUserMapper.selectOneByExample(example);

        ProxyUser proxyUserUpdate = new ProxyUser();
        proxyUserUpdate.setId(proxyUser.getId());
        proxyUserUpdate.setUpdateTime(date);
        proxyUserUpdate.setPhone(partner.getPhone());
        proxyUserUpdate.setTrueName(partner.getFullName());
        proxyUserMapper.updateByPrimaryKeySelective(proxyUserUpdate);

        partner.setUpdateTime(date);
        partner.setShareRatio(new BigDecimal(100).subtract(partner.getProjectShareRatio()));
        return partnerMapper.updateByPrimaryKeySelective(partner);
    }

    /**
     * @param parentId 合作商ID
     * @return
     */
    @Override
    public int selectCountByParentId(String parentId) {
        Example example = new Example(Partner.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("parentId", parentId);
        criteria.andEqualTo("isDelete", YesOrNoEnum.NO.getCode());
        return partnerMapper.selectCountByExample(example);
    }

    /**
     * 逻辑删除合作商
     *
     * @param id
     * @return
     */
    @Override
    public int deleteLogicPartnerById(String id) {

        Date date = new Date();
        // 逻辑删除合作商
        Partner updatePartner = new Partner();
        updatePartner.setId(id);
        updatePartner.setIsDelete(YesOrNoEnum.YES.getCode());
        updatePartner.setUpdateTime(date);
        partnerMapper.updateByPrimaryKeySelective(updatePartner);

        PartnerInstall installUpdate = new PartnerInstall();
        installUpdate.setPartnerId(id);
        installUpdate.setIsDelete(YesOrNoEnum.YES.getCode());
        partnerInstallMapper.updateByPrimaryKeySelective(installUpdate);

        // 逻辑删除
        ProxyUser updateProxyUser = new ProxyUser();
        updateProxyUser.setUpdateTime(date);
        updateProxyUser.setIsDeleted(YesOrNoEnum.YES.getCode());
        Example example = new Example(ProxyUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("accountType", AccountTypeEnum.PARTNER.getCode());
        criteria.andEqualTo("accountId", id);
        return proxyUserMapper.updateByExampleSelective(updateProxyUser, example);
    }


    /**
     * 查询合作商树列表
     *
     * @return 所有合作商信息
     */
    @Override
    public List<Ztree> selectPartnerTree() {
        List<Partner> partnerList = partnerMapper.selectPartnerList(new Partner());
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (Partner partner : partnerList) {
            Ztree ztree = new Ztree();
            ztree.setId(partner.getId());
            ztree.setpId(partner.getParentId());
            ztree.setName(partner.getFullName() + " " + partner.getPhone());
            ztree.setTitle(partner.getFullName());
            ztrees.add(ztree);
        }
        return ztrees;
    }

    @Override
    public List<PartnerVV> selectPartnerVOLists(String id, int i) {
        return partnerMapper.selectPartnerVOLists(id, i);
    }

    @Override
    public PartnerVV selectPartnerVOListsById(String id) {
        return partnerMapper.selectPartnerVOListsById(id);
    }

    /**
     * 查询顶级合作商列表
     *
     * @return
     */
    @Override
    public List<PartnerVO> selectHeadPartnerVOList() {
        return partnerMapper.selectHeadPartnerVOList();
    }

    @Override
    public PartnerUser selectApplyCount(String id) {
        return partnerMapper.selectApplyCount(id);
    }

    @Override
    public Finance selectFinanceCount(JSONObject json) {
        Finance finance = null;
        String id = json.getStr("id");
        // 账号类型 1 平台 2 合作商 3 商户
        if (json.getInt("type") == 2) {
            PartnerInstall install = partnerInstallMapper.selectByPrimaryKey(id);
            finance = partnerMapper.selectFinancePartner(id);
            finance.setTxBrokerage(install.getTxBrokerage());
            finance.setTxMinPermit(install.getTxMinPermit());
        } else {
            // 3 -- 商户
            MerchantInstall install = merchantInstallMapper.selectByPrimaryKey(id);
            finance = partnerMapper.selectFinanceMerchant(id);
            finance.setTxBrokerage(install.getTxBrokerage());
            finance.setTxMinPermit(install.getTxMinPermit());
        }

        if (finance != null) {
            List<DictDataVO> showlist = configService.selectDictDataByTypeStr("tx_show_describe");
            finance.setShowlist(showlist);

            String costReate = configService.selectConfigByKeyNoCache("tx_cost_rate"); // (微信/支付宝/银行卡)提现手续费
            finance.setCostReate(new BigDecimal(costReate));
        }

        if (finance != null && StringUtils.isNotBlank(finance.getAppOpenid())) {
            // 微信小程序提现
            Example example = new Example(AppUser.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("appUserCode", finance.getAppOpenid());
            AppUser appUser = appUserMapper.selectOneByExample(example);
            finance.setWxMinAppUser(appUser);
        }
        if (finance != null && null != finance.getAppWxId()) {
            Example example = new Example(AppUser.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("appUserCode", finance.getAppWxId());
            AppUser appUser = appUserMapper.selectOneByExample(example);
            finance.setWxAppUser(appUser);
        }
        if (finance != null && null != finance.getAppAliId()) {
            Example example = new Example(AppUser.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("appUserCode", finance.getAppAliId());
            AppUser appUser = appUserMapper.selectOneByExample(example);
            finance.setAliAppUser(appUser);
        }
        return finance;
    }

    /**
     * 查询合作商营业额top6
     *
     * @return
     */
    @Override
    public List<Partner> selectPartnerTop6List() {
        return partnerMapper.selectPartnerTop6List();
    }

    /**
     * 设备-调拨专用 用于获取合作商信息包含他自身
     *
     * @param accountId
     * @return
     */
    @Override
    public List<PartnerDevAllotVO> selectPartnersDevAllot(String accountId, String keywords) {
        return partnerMapper.selectPartnersDevAllot(accountId, keywords);
    }

    /**
     * 合作商 统计分析
     *
     * @param id
     * @return
     */
    @Override
    public PartnerVO selectStatisticalAnalysisVo(String id) {
        return partnerMapper.selectStatisticalAnalysisVo(id);
    }

    @Override
    public List<Ztree> selectPartnerTreeSelf(String id) {

        // 查询该合作商的子节点
        String partnerChildIdStrAndSelf = partnerMapper.getPartnerChildIdStrAndSelf(id);
        if (StringUtils.isBlank(partnerChildIdStrAndSelf)) {
            partnerChildIdStrAndSelf = "";
        }
        // 查询该合作商的父节点
        String parentsIds = partnerMapper.selectAllParentsIds(id);
        if (StringUtils.isBlank(parentsIds)) {
            parentsIds = "";
        }

        List<Partner> partnerList = partnerMapper.selectPartnerList(new Partner());
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (Partner partner : partnerList) {
            if (partnerChildIdStrAndSelf.contains(partner.getId())) {
                Ztree ztree = new Ztree();
                ztree.setId(partner.getId());
                ztree.setpId(partner.getParentId());
                ztree.setName(partner.getFullName() + " " + partner.getPhone());
                ztree.setTitle(partner.getFullName());
                ztrees.add(ztree);
            } else if (parentsIds.contains(partner.getId())) {
                Ztree ztree = new Ztree();
                ztree.setId(partner.getId());
                ztree.setpId(partner.getParentId());
                ztree.setName(partner.getFullName() + " " + partner.getPhone());
                ztree.setTitle(partner.getFullName());
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }
}
